const KoaRouter = require('koa-router')
const path = require('path');
const {runShell} = require("../helper/shell");
const {callCmd} = require("../helper/shell");
const {getData} = require("../helper/request");
const {writeFile} = require("../helper/file");
const {readFile} = require("../helper/file");

const router = new KoaRouter()

// 在服务端运行 shell 命令
router.get(`/runShell`, async (ctx) => {
    const { cmd } = ctx.request.query
    const res = await runShell(cmd)
    ctx.body = res;
})
// 调用系统cmd窗口
router.get(`/callCmd`, async (ctx) => {
    const { cmd } = ctx.request.query
    callCmd(cmd)
    ctx.body = 'res';
})
// 通过接口查询 npm 包的信息
router.get(`/getNpmInfo`, async (ctx) => {
    const { name } = ctx.request.query
    const res = await  getData('https://registry.npmjs.org/'+name)
    ctx.body = res.body;
})
// 通过接口查询 Git 包的信息
router.get(`/getGitInfo`, async (ctx) => {
    const res = await runShell('git log origin/master')
    ctx.body = res;
})
// 更新 Git
router.post(`/updateGit`, async (ctx) => {
    const { commit } = ctx.request.body
    const add = await runShell('git add .')
    const pull = await runShell('git pull origin master')
    const commitInfo = await runShell('git commit -m ' + commit)
    const push = await runShell('git push origin master')
    ctx.body = {add,pull,commitInfo,push}
})
// 更新本地的package.json
router.post(`/updateNpm`, async (ctx) => {
    const { version,description } = ctx.request.body
    const p = path.resolve('./functions/package.json')
    return new Promise((resolve => {
        readFile(p,content=>{
            resolve(JSON.parse(content))
        })
    })).then(async res=>{
        res.version = version
        if(description){
            res.description = description
        }
        const writeRes = await writeFile(p,JSON.stringify(res))
        ctx.body = writeRes;
    })
})
// 更新npm包
router.get(`/publishNpm`, async (ctx) => {
    const {dir}  = ctx.request.query
    const res = await runShell('npm publish ' + dir)
    console.log(res)
    ctx.body = res
})

module.exports = router
